package com.budwk.app.base.gmpass;

import com.budwk.starter.common.constant.RedisConstant;
import com.budwk.starter.common.result.Result;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;

import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;

/**
 * 国产密码统一使用工具业务类
 */
@IocBean
public class GmPwdUtilService {
    @Inject
    private RedisService redisService;
    /**
     * 密码加盐-用于密码和数据库密码比对
     * @param password 密码
     * @param salt 盐
     * @return 返回加盐的密码字符串
     */
    public String getPwdSlat(String password,String salt) {

        return SM3Util.getPassword(password,salt);
    }

    /**
     * 客户端和服务器交换公钥钥匙
     * @param clientkey 客户端提供的公钥
     * @return 服务器生成的公钥
     */
    public Result getPublicKey(String clientkey) {
        SM2Util sm2Util = new SM2Util();
        try {
            KeyPair keyPair = sm2Util.geneSM2KeyPair();
            //公钥
            String publicKey = sm2Util.getPubKeyHexString(keyPair.getPublic());
            String privateKey = sm2Util.getPriKeyHexString(keyPair.getPrivate());
            //生成一个临时的key，在拥有token之前
            String rsaKey = R.UU32();
            String redisv = Json.toJson(NutMap.NEW().addv("privateKey", privateKey).addv("spublicKey", publicKey).addv("cpublicKey",clientkey));
            redisService.setex(RedisConstant.PRE + "ucenter:sm2:" + rsaKey, 3600, redisv);
            //加密公钥

            return Result.success(NutMap.NEW().addv("sm2Key", rsaKey).addv("sm2PublicKey", publicKey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  Result.error("获取口令失败");
    }



}
